import type { SystemTheme, UserInfo, UserToken } from './type'
import { StorageKey } from '@/provider/storage/enum'
import StorageProvider from '@/provider/storage'
import { toTimestamp, genRandomPassword } from './hooks/utils'

/**
 * 用户服务类
 *
 * @description 管理用户相关功能与信息
 */
class xUserService {
  // 静态属性存储唯一实例
  private static instance: xUserService

  /**
   * 服务初始化（全局仅执行一次）
   */
  private constructor() {}
  /**
   * 获取单例实例
   *
   * @returns
   */
  public static getInstance = () => {
    if (!xUserService.instance) {
      xUserService.instance = new xUserService()
    }
    return xUserService.instance
  }

  /**
   * 读取设备ID
   *
   * @returns
   */
  public getDeviceId = () => {
    let deviceId = StorageProvider.getLocalStorage<string>(StorageKey.UserDevice)
    if (!deviceId) {
      // 未找到设备ID，新生成
      deviceId = genRandomPassword({
        length: 32,
        includeNumbers: true,
        includeLowercase: true,
        includeUppercase: true,
        includeSymbols: false,
      })
      StorageProvider.setLocalStorage(StorageKey.UserDevice, deviceId)
    }
    return deviceId
  }

  /**
   * 读取用户信息
   *
   * @returns
   */
  public getUserInfo = () => {
    return StorageProvider.getLocalStorage<UserInfo>(StorageKey.UserInfo, {
      // 填充默认值（未存储时）
      uid: 0,
      username: '',
      nickname: '',
      phone: '',
      email: '',
      remark: '',
    })
  }

  /**
   * 写入用户信息
   *
   * @param data 数据
   * @returns
   */
  public setUserInfo = (data: UserInfo) => {
    return StorageProvider.setLocalStorage(StorageKey.UserInfo, data)
  }

  /**
   * 获取访问Token（过期判断）
   *
   * @returns
   */
  public getAccessToken = () => {
    const token = StorageProvider.getLocalStorage<UserToken>(StorageKey.UserToken)
    if (token && token?.accessToken && token?.expires > Date.now()) {
      return token.accessToken
    }
    return ''
  }

  /**
   * 获取刷新Token
   *
   * @returns
   */
  public getRefreshToken = () => {
    const token = StorageProvider.getLocalStorage<UserToken>(StorageKey.UserToken)
    return token?.refreshToken ?? ''
  }

  /**
   * 写入用户Token
   *
   * @param accessToken 访问Token
   * @param refreshToken 刷新Token
   * @param expires 过期时间（支持多种格式）
   * @returns
   */
  public setUserToken = (
    accessToken: string,
    refreshToken: string,
    expires: Date | number | string,
  ) => {
    return StorageProvider.setLocalStorage<UserToken>(StorageKey.UserToken, {
      accessToken,
      refreshToken,
      expires: toTimestamp(expires),
    })
  }

  /**
   * 清除用户信息与token
   *
   * @returns
   */
  public clearUserData = () => {
    StorageProvider.setLocalStorage(StorageKey.UserInfo, null)
    StorageProvider.setLocalStorage(StorageKey.UserToken, null)
  }

  /**
   * 读取系统主题
   *
   * @returns
   */
  public getSystemTheme = () => {
    return StorageProvider.getLocalStorage<SystemTheme>(StorageKey.ThemeMode, 'light')
  }

  /**
   * 设置系统主题
   *
   * @param theme
   */
  public setSystemTheme = (theme: SystemTheme) => {
    StorageProvider.setLocalStorage(StorageKey.ThemeMode, theme)
  }

  /**
   * 清空本地存储
   */
  public clearLocalStorage = async () => {
    await StorageProvider.clearAll()
  }
}

export default xUserService
